import { init, styleModule, classModule, eventListenersModule, h } from "snabbdom"
import _ from "lodash"
import contentData from "./contentData";

const patch = init([
	styleModule,
	classModule,
	eventListenersModule,
])

const container = document.getElementById("app");

let sortBy ,oldnode

let setData = _.cloneDeep(contentData)

function newDom(data) {
	return h("div.contentBody", [
		h("h1", { style: { fontWeight: "bold" } }, "Top 10 movies"),
		h("div", [
			"Sort by:",
			h("span.btn", {on: { click: () => clickSort("rank") }, class: { active: sortBy === "rank" }}, "Rank"),
			h("span.btn", {on: { click: () => clickSort("title") }, class: { active: sortBy === "title" }}, "Title"),
			h("span.btn", {on: { click: () => clickSort("desc") }, class: { active: sortBy === "desc" }}, "Description"),
			h("span.btn", {on: { click: add }, style: { marginLeft: "100px" }}, "Add"),
		]),
		h("div.list", data.map((res, index) => {
			return h("div.listContent", [
				h("p.rank", res.rank),
				h("p.title", res.title),
				h("p.desc", res.desc),
				h("p.del", {on: { click: () => del(index) }}, "X"),
			])
		})),
	])
}
// 初始化
oldnode = patch(container, newDom(setData));

function render() {
	oldnode = patch(oldnode, newDom(setData));
}

function clickSort(res) {
	sortBy = res
	setData = _.sortBy(setData, sortBy)
	render()
}

function del(index) {
	_.pullAt(setData, index)
	render()
}

function add() {
	console.log("add")
	sortBy = ""
	const addData = _.cloneDeep(contentData[Math.floor(Math.random()*10)])
	addData.rank = Math.ceil(Math.random()*100) + 1
	setData = [addData, ...setData]
	render()
}